class_name Utils



#region SimpleTimer
class SimpleTimer:
    
    var _running: bool
    var _start_time: int
    var _last_time: int
    var _interval: float
    var _duration: float
    var _callback: Callable
    
    func _init(interval: float, duration: float, callback: Callable) -> void:
        _interval = interval
        _duration = duration
        _callback = callback
    
    
    func update() -> void:
        if not _running: return
        
        if Time.get_ticks_msec() - _start_time >= _duration * 1000:
            _running = false
        
        if Time.get_ticks_msec() - _last_time >= _interval * 1000:
            _callback.call()
            _last_time = Time.get_ticks_msec()

    
    func start() -> void:
        _start_time = Time.get_ticks_msec()
        _last_time = Time.get_ticks_msec()
        _running = true
        _callback.call()
#endregion


#region static functions
static func get_input_vec2() -> Vector2:
    return Input.get_vector("move_left", "move_right", "move_up", "move_down")


## 参数 probability: 概率，取值范围[0, 1]
static func prize_draw(probability: float) -> bool:
    probability = clampf(probability, 0.0, 1.0)
    return randf() < probability


## 自动查找map节点下的TileMapLayer节点，获取包含所有TileMapLayer的used_rect的rect
static func get_map_max_rect(map: Node2D) -> Rect2i:
    var rect := Rect2i(0, 0, 0, 0)

    for child in map.get_children():
        if child is not TileMapLayer: continue
        var used_rect := child.get_used_rect() as Rect2i
        rect = rect.merge(used_rect)

    return rect


## 在指定的矩形内生成随机的点
static func random_point_from_rect(rect: Rect2) -> Vector2:
    var point := Vector2.ZERO
    point.x = randf_range(rect.position.x, rect.position.x + rect.size.x)
    point.y = randf_range(rect.position.y, rect.position.y + rect.size.y)
    return point


## 获取窗口显示内容在全局坐标中的矩形，any_node必须是在场景树中的节点
static func get_visible_global_rect(any_node: Node) -> Rect2:
    var viewport = any_node.get_viewport()
    var local_rect = viewport.get_visible_rect()
    var global_top_left = viewport.canvas_transform.affine_inverse() * local_rect.position
    var global_size = local_rect.size / viewport.canvas_transform.get_scale()
    return Rect2(global_top_left, global_size)


static func random_from_vec2(vec2: Vector2) -> float:
    return randf_range(vec2.x, vec2.y)

#endregion